#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow( QString config_path, QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    ,_setting(config_path, QSettings::IniFormat)
{
    ui->setupUi(this);


    Init();
}

MainWindow::~MainWindow()
{
    CloseCameras();

    _plc_thread->quit();
    _plc_thread->wait();

    _log_thread->quit();
    _log_thread->wait();

    delete ui;
    qDebug()<<"~MainWindow()";
}

void MainWindow::LoadConfig()
{
    _camera_count = _setting.value("camera_count", 1).toInt();
    ui->lineEdit_13->setText(QString::number(_camera_count));
    _camera_param.resize(_camera_count);

    if(_camera_count>=1) {
        QString A_text =  _setting.value("A1", "300, 240, 340, 240, 380, 270, 260, 270").toString();
        QString B_text =  _setting.value("B1", "62, 0, 69, 0, 48, 30, 80, 30").toString();

        ui->A1->setText(A_text);
        ui->B1->setText(B_text);

        QStringList A_list =A_text.trimmed().split(",");
        QStringList B_list =B_text.trimmed().split(",");
        if(A_list.size()>=8 && B_list.size()>=8){
            for(int i =0;i<8;i++){
                _camera_param[0].A[i] = A_list[i].toInt();
                _camera_param[0].B[i] = B_list[i].toInt();
            }
        }

        QString C_text =  _setting.value("C1", "210").toString();
        QString D_text =  _setting.value("D1", "65").toString();
        ui->C1->setText(C_text);
        ui->D1->setText(D_text);

        _camera_param[0].C = C_text.toInt();
        _camera_param[0].D = D_text.toInt();
        ui->pushButton->setEnabled(true);
    }

    if(_camera_count>=2) {
        QString A_text =  _setting.value("A2", "309, 150, 328, 150, 377, 190, 265, 190").toString();
        QString B_text =  _setting.value("B2", "53, 0, 50, 0, 32, 40, 72, 40").toString();

        ui->A2->setText(A_text);
        ui->B2->setText(B_text);

        QStringList A_list =A_text.trimmed().split(",");
        QStringList B_list =B_text.trimmed().split(",");
        if(A_list.size()>=8 && B_list.size()>=8){
            for(int i =0;i<8;i++){
                _camera_param[1].A[i] = A_list[i].toInt();
                _camera_param[1].B[i] = B_list[i].toInt();
            }
        }

        QString C_text =  _setting.value("C2", "95").toString();
        QString D_text =  _setting.value("D2", "92").toString();
        ui->C2->setText(C_text);
        ui->D2->setText(D_text);

        _camera_param[1].C = C_text.toInt();
        _camera_param[1].D = D_text.toInt();
        ui->pushButton_4->setEnabled(true);
    }

    if(_camera_count>=3) {
        QString A_text =  _setting.value("A3", "300, 240, 340, 240, 380, 270, 260, 270").toString();
        QString B_text =  _setting.value("B3", "62, 0, 69, 0, 48, 30, 80, 30").toString();

        ui->A3->setText(A_text);
        ui->B3->setText(B_text);

        QStringList A_list =A_text.trimmed().split(",");
        QStringList B_list =B_text.trimmed().split(",");
        if(A_list.size()>=8 && B_list.size()>=8){
            for(int i =0;i<8;i++){
                _camera_param[2].A[i] = A_list[i].toInt();
                _camera_param[2].B[i] = B_list[i].toInt();
            }
        }

        QString C_text =  _setting.value("C3", "210").toString();
        QString D_text =  _setting.value("D3", "65").toString();
        ui->C3->setText(C_text);
        ui->D3->setText(D_text);

        _camera_param[2].C = C_text.toInt();
        _camera_param[2].D = D_text.toInt();
        ui->pushButton_5->setEnabled(true);
    }
}



void MainWindow::ConfigUi()
{
    ui->tabWidget->setCurrentIndex(0);
}

void MainWindow::Init()
{
    ConfigUi();

    LoadConfig();

    OpenThread();

    OpenCameras();
}

void MainWindow::OpenThread()
{
    //log
    _log_thread = new QThread;
    _log = new Log;
    connect(_log_thread, &QThread::started, _log, &Log::RecordLog);
    connect(_log_thread, &QThread::finished, _log, &Log::deleteLater);
    _log->moveToThread(_log_thread);
    _log_thread->start();
    QThread::msleep(1); //日志启动需要时间

    //plc
    _plc_thread = new QThread;
    _plc = new Plc;
    connect(_plc_thread, &QThread::started, _plc, &Plc::ConnectToPlc);
    connect(_plc_thread, &QThread::finished, _plc, &Plc::deleteLater); //这种写法保证可以正确析构
    connect(this,&MainWindow::pause_req_vision,_plc,&Plc::PauseReqVision);
    _plc->moveToThread(_plc_thread);
    _plc_thread->start();

}

void MainWindow::OpenCameras()
{
    for (int i = 0; i < _camera_count; i++) {
        QThread* cam_thread = new QThread;
        Camera* cam_woker = new Camera(i,_camera_param[i]); //初始传递参数

        connect(cam_woker, &Camera::show_camera, this, &MainWindow::ShowCamera);
        //connect(this, &MainWindow::update_camparam, cam_woker, &Camera::UpdateParam);
        connect(cam_thread, &QThread::started, cam_woker, &Camera::Open);
        connect(cam_thread, &QThread::finished, cam_woker, &Camera::deleteLater);
        cam_woker->moveToThread(cam_thread);

        // 线程启动时，开始摄像头
        _camera_threads[i] = cam_thread;
        _camera_workers[i] = cam_woker;

        cam_thread->start();
        QThread::msleep(200); //摄像头启动需要时间，同时启动会导致正常的显示不出来
    }
}

void MainWindow::CloseCameras()
{

    for (auto it = _camera_threads.begin(); it != _camera_threads.end(); ++it) {
        int index = it.key();
        Camera* worker = _camera_workers[index];
        QThread* thread = it.value();

        if (worker) {
            worker->deleteLater();
        }

        if (thread) {
            thread->quit();
            thread->wait();
            thread->deleteLater();
        }
    }

    _camera_threads.clear();
    _camera_workers.clear();
}



void MainWindow::ShowCamera(const int& camera_index, const QImage& img)
{
    QLabel* label=nullptr;
    switch(camera_index){
        case 0:
            label = ui->camera1;
            break;
        case 1:
            label = ui->camera2;
            break;
        case 2:
            label = ui->camera3;
            break;
        default:
            qCritical() << "相机索引不正确："<<camera_index;
            return;
    }
    //qDebug()<<"camera_index = "<<camera_index;
    label->setPixmap(QPixmap::fromImage(img).scaled(label->size(), Qt::KeepAspectRatio)); // 显示在 QLabel 上
}



void MainWindow::on_pushButton_clicked()
{
    _setting.setValue("A1", ui->A1->text());
    _setting.setValue("B1", ui->B1->text());
    _setting.setValue("C1", ui->C1->text());
    _setting.setValue("D1", ui->D1->text());

    QStringList A = ui->A1->text().trimmed().split(",");
    if(A.size()<8) {
        QMessageBox::critical(this, "错误", "camera1的A参数少于8个");
        return;
    }

    QStringList B = ui->B1->text().trimmed().split(",");
    if(B.size()<8) {
        QMessageBox::critical(this, "错误", "camera1的B参数少于8个");
        return;
    }

    QString C = ui->C1->text().trimmed();
    QString D = ui->D1->text().trimmed();
    if(C==""||D==""){
        QMessageBox::critical(this, "错误", "camera1的C或D参数为空！");
        return;
    }

    for(int i =0;i<8;i++){
        _camera_param[0].A[i] = A[i].toInt();
        _camera_param[0].B[i] = B[i].toInt();
    }
    _camera_param[0].C = C.toInt();
    _camera_param[0].D = D.toInt();

    QMessageBox::information(this, "ok", "参数保存成功");
    QMetaObject::invokeMethod(_camera_workers[0], "UpdateParam", Qt::QueuedConnection, Q_ARG(CamParam, _camera_param[0])); //采用信号的话会广播，所以直接调用排队到对应camera线程
}


void MainWindow::on_pushButton_2_clicked()
{
    if(ui->pushButton_2->text()=="手动开启视觉"){
        emit pause_req_vision(true);

        ui->pushButton_2->setText("手动关闭视觉");
    }else{
        emit pause_req_vision(false);
        ui->pushButton_2->setText("手动开启视觉");
    }
}



void MainWindow::on_pushButton_4_clicked()
{
    _setting.setValue("A2", ui->A2->text());
    _setting.setValue("B2", ui->B2->text());
    _setting.setValue("C2", ui->C2->text());
    _setting.setValue("D2", ui->D2->text());

    QStringList A = ui->A2->text().trimmed().split(",");
    if(A.size()<8) {
        QMessageBox::critical(this, "错误", "camera2的A参数少于8个");
        return;
    }

    QStringList B = ui->B2->text().trimmed().split(",");
    if(B.size()<8) {
        QMessageBox::critical(this, "错误", "camera2的B参数少于8个");
        return;
    }

    QString C = ui->C2->text().trimmed();
    QString D = ui->D2->text().trimmed();
    if(C==""||D==""){
        QMessageBox::critical(this, "错误", "camera2的C或D参数为空！");
        return;
    }

    for(int i =0;i<8;i++){
        _camera_param[1].A[i] = A[i].toInt();
        _camera_param[1].B[i] = B[i].toInt();
    }
    _camera_param[1].C = C.toInt();
    _camera_param[1].D = D.toInt();

    QMessageBox::information(this, "ok", "参数保存成功");
    QMetaObject::invokeMethod(_camera_workers[1], "UpdateParam", Qt::QueuedConnection, Q_ARG(CamParam, _camera_param[1]));
}


void MainWindow::on_pushButton_5_clicked()
{
    _setting.setValue("A3", ui->A3->text());
    _setting.setValue("B3", ui->B3->text());
    _setting.setValue("C3", ui->C3->text());
    _setting.setValue("D3", ui->D3->text());

    QStringList A = ui->A3->text().trimmed().split(",");
    if(A.size()<8) {
        QMessageBox::critical(this, "错误", "camera3的A参数少于8个");
        return;
    }

    QStringList B = ui->B3->text().trimmed().split(",");
    if(B.size()<8) {
        QMessageBox::critical(this, "错误", "camera3的B参数少于8个");
        return;
    }
    QString C = ui->C3->text().trimmed();
    QString D = ui->D3->text().trimmed();

    if(C==""||D==""){
        QMessageBox::critical(this, "错误", "camera3的C或D参数为空！");
        return;
    }

    for(int i =0;i<8;i++){
        _camera_param[2].A[i] = A[i].toInt();
        _camera_param[2].B[i] = B[i].toInt();
    }
    _camera_param[2].C = C.toInt();
    _camera_param[2].D = D.toInt();

    QMessageBox::information(this, "ok", "参数保存成功");
    QMetaObject::invokeMethod(_camera_workers[2], "UpdateParam", Qt::QueuedConnection, Q_ARG(CamParam, _camera_param[2]));
}


void MainWindow::on_pushButton_3_clicked()
{
    _setting.setValue("camera_count", ui->lineEdit_13->text());
    QMessageBox::information(this, "ok", "保存成功");
}

